package com.dailyblue.project.estate.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.project.estate.commons.bean.Building;
import com.dailyblue.project.estate.commons.handler.BuildingException;
import com.dailyblue.project.estate.commons.mapper.BuildingMapper;
import com.dailyblue.project.estate.commons.util.JsonResult;
import com.dailyblue.project.estate.commons.util.ResultTool;
import com.dailyblue.project.estate.service.BuildingService;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther:Liu
 * @Testname:BuildingServiceImpl
 * @Date:2025/9/18 11:24
 */
@Service
public class BuildingServiceImpl extends ServiceImpl<BuildingMapper, Building> implements BuildingService {

    @Resource
    private BuildingMapper buildingMapper;
    @Override
    public JsonResult saveBuilding(Building building) {
        boolean b = save(building);
        if (!b) {
            throw new BuildingException("添加失败");
        }
        return ResultTool.success("save success");
    }

    @Override
    public JsonResult findBuildingById(String id) {
        Building building = getById(id);
        return ResultTool.success(building);
    }

    @Cacheable(cacheNames = "Buildings")
    public JsonResult findBuildingsAll() {
        List<Building> list = list();
        return ResultTool.success(list);
    }

    @CacheEvict(cacheNames = "Buildings", allEntries = true)
    public JsonResult deleteBuilding(String id) {
        boolean b = super.removeById(id);
        if (!b) {
            throw new BuildingException("删除失败");
        }
        return ResultTool.success("delete success");
    }

    @CacheEvict(cacheNames = "Buildings",allEntries = true)
    public JsonResult updateBuilding(Building building) {
        UpdateWrapper<Building> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", building.getId());
        wrapper.set("name", building.getName());
        wrapper.set("description", building.getDescription());
        wrapper.set("community_id", building.getCommunityId());
        wrapper.set("community_name", building.getCommunityName());
        wrapper.set("total_households", building.getTotalHouseholds());
        int update = buildingMapper.update(wrapper);
        if (update >=0) {
            return ResultTool.success("更新成功");
        }else{
            throw new BuildingException("更新失败");
        }
    }
}
